package com.zhongshengnetwork.rightbe.login;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.sax.RootElement;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.MD5;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.BDCodeModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class VerifyActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private TopBarView topbar;
    private EditText accountText;
    private EditText codeText;
    private Button codeBt;
    private EditText passwordText;
    private TextView tip_text;
    private boolean isHasUser = false;

    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private Handler mHandler = null;
    private final static int TimeOut = 91;
    private int timeCount = 0;
    private static int delay = 1000;  //1s
    private static int period = 1000;  //1s

    private int type; //0-手机验证码；1-密码
    private String mobile; //手机号
    private AVLoadingIndicatorView avi;

    private String getMobile(String mobile){
        String str = "";
        for (int i = 0; i < mobile.length(); i++) {
            if (i == mobile.length()-11) {
                str += mobile.charAt(i);
            } else if(i == mobile.length()-10) {
                str += mobile.charAt(i);
            }else if(i == mobile.length()-9) {
                str += mobile.charAt(i);
            }else if(i == mobile.length()-3) {
                str += mobile.charAt(i);
            }else if(i == mobile.length()-2) {
                str += mobile.charAt(i);
            }else if(i == mobile.length()-1) {
                str += mobile.charAt(i);
            }else {
                str += "*";
            }
        }
        return str;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify);
        type = getIntent().getIntExtra(APIKey.typeKey,0);
        mobile = getIntent().getStringExtra("mobile");
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);

        topbar.getRightTextView().setVisibility(View.VISIBLE);
        topbar.getRightTextView().setText("下一步");
        topbar.getRightTextView().setTextSize(16);
        topbar.getRightTextView().setTextColor(getResources().getColor(R.color.mainColor));
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                bdThird();
            }
        });

        tip_text = (TextView) findViewById(R.id.tip_text);
        tip_text.setTextColor(AppThemeUtils.getInstance().getLightTextColor());
        accountText = (EditText) findViewById(R.id.bd_account);
        codeText = (EditText) findViewById(R.id.bd_codetext);
        codeBt = (Button) findViewById(R.id.bd_codebt);
        passwordText = (EditText) findViewById(R.id.bd_password);
        passwordText.setVisibility(View.VISIBLE);

        LinearLayout activity_bdthird = (LinearLayout) findViewById(R.id.activity_bdthird);
        activity_bdthird.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

        accountText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        accountText.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        accountText.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        codeText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        codeText.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        codeText.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        passwordText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        passwordText.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        passwordText.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        codeBt.setBackgroundResource(AppThemeUtils.getInstance().getComsytleBg());

        codeBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                getCode();
            }
        });

        if(type == 0){
            topbar.getTitleView().setText("验证旧手机");
            tip_text.setText("点击获取验证码，然后输入验证码进入下一步");
            accountText.setHint(getMobile(mobile));
            accountText.setEnabled(false);
            passwordText.setVisibility(View.GONE);
        }else if (type == 1){
            tip_text.setText("请输入登录密码，然后进入下一步");
            topbar.getTitleView().setText("验证登录密码");
            accountText.setHint(getMobile(mobile));
            accountText.setEnabled(false);
            codeText.setVisibility(View.GONE);
            codeBt.setVisibility(View.GONE);
            passwordText.setVisibility(View.VISIBLE);
            LinearLayout up_line = (LinearLayout) findViewById(R.id.up_line);
            up_line.setVisibility(View.GONE);
            RelativeLayout code_layout = (RelativeLayout) findViewById(R.id.code_layout);
            code_layout.setVisibility(View.GONE);
        }

        // 定义Handler
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg == null){
                    return;
                }
                //handler处理消息
                if(msg.what>0){
                    codeBt.setText(msg.what+"秒");
                }else{
                    //在handler里可以更改UI组件
                    stopTimer();
                    codeBt.setText("获取验证码");
                }
            }
        };
    }
    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        hintKeyBoard();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void startTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
        }

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (timeCount > 0){
                        timeCount--;
                    }
                    sendMessage(timeCount);
                }
            };
        }

        if(mTimer != null && mTimerTask != null ){
            if (timeCount == 0){
                timeCount = TimeOut;
                mTimer.schedule(mTimerTask, delay, period);
            }
        }

    }

    private void stopTimer(){
        if (mTimer != null) {
            timeCount = 0;
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        codeBt.setClickable(true);
        timeCount = 0;
    }

    public void sendMessage(int id){
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    //获取验证码
    private void getCode(){
        if (timeCount > 0){
            return;
        }
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.accountKey, mobile);
        map.put(APIKey.typeKey, "4");
        map.put("token", CustomApplication.loginModel.getToken());
        HttpsUtils.getCodeDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    startTimer();
                }else {
                    ToastUtil.show(VerifyActivity.this,commonModel.getMsg());
                    stopTimer();
                    codeBt.setText("获取验证码");
                    codeBt.setClickable(true);
                    return;
                }
            }

            @Override
            public void onError(String msg) {
                stopTimer();
                codeBt.setText("获取验证码");
                codeBt.setClickable(true);
            }
        });
    }

    //绑定第三方账号
    private void bdThird(){

        if (type == 0){
            //检查数据是否完整
            if (codeText.getText().toString().trim().length() < 6){
                ToastUtil.show(VerifyActivity.this,"请输入6位验证码");
                return;
            }
        }else if (type == 1){
            if (passwordText.getText().toString().trim().length() < 1){
                ToastUtil.show(VerifyActivity.this,"请输入登录密码");
                return;
            }
        }

        avi.show();
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.typeKey,""+type);
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        if (type == 0){
            map.put("randcode",codeText.getText().toString());
            map.put(APIKey.accountKey,mobile);
        }else if (type == 1){
            map.put(APIKey.passwordKey, MD5.GetMD5Code(passwordText.getText().toString()));
        }
        HttpsUtils.verifyaccountDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    ToastUtil.show(VerifyActivity.this, "验证成功~");
                    String passport = commonModel.getMsg();
                    Intent intent = new Intent();
                    intent.putExtra("passport", passport);
                    setResult(RESULT_OK, intent);//设置resultCode
                    finish();
                }else {
                    ToastUtil.show(VerifyActivity.this, commonModel.getMsg());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
                ToastUtil.show(VerifyActivity.this,"验证失败");
            }
        });

    }


}
